import { makeAutoObservable } from 'mobx';
import * as api from './api';

/**
 * 样板： https://mobx.js.org/defining-data-stores.html
 *       https://mobx.js.org/react-integration.html
 * 基本用作UI store，尽量避免前端包含复杂数据逻辑
 */

export default class DictStore {
  pageSize = PGSIZE;
  pageNo = 1;
  keyword = undefined;
  data = [];
  total = 0;
  loading = false;

  constructor(rootStore) {
    makeAutoObservable(this);
  }

  api() {
    return api;
  }

  /**
   * 发起获取列表
   */
  * fetch() {
    this.loading = true;
    try {
      this.total = yield api.countDict({ keyword: this.keyword });
      this.data = yield api.searchDict({ keyword: this.keyword, page: (this.pageNo - 1), size: this.pageSize }); // , sort: 'crDate;desc,_id;desc'
      // this.current = this.data.length > 0 ? this.data[0] : {};
    } finally {
      this.loading = false;
    }
  }

  reset() {
    this.keyword = '';
    this.pageNo = 1;
    this.fetch();
  }

  setSizeList(val) {
    if (val === this.pageSize) return;
    this.pageSize = val;
    this.fetch();
  }

  setPageNo(val) {
    if (val === this.pageNo) return;
    this.pageNo = val;
    this.fetch();
  }

  setKeyword(val) {
    if (val === this.keyword) return;
    this.keyword = val;
    if (val === '') this.fetch();
  }

  /**
   * 创建字典
   * @param {object} dict 待添加的字典
   * @returns 创建后的字典
   */
  create(dict) {
    return api.createDict(dict).then((d) => {
      this.reset();
      return d;
    });
  }

  /**
   * 创建字典
   * @param {object} dict 待添加的字典
   * @returns 创建后的字典
   */
  update(dict) {
    return api.updateDict(dict).then((d) => {
      this.fetch();
      return d;
    });
  }

  /**
   * 删除字典
   * @param {string} dictId 字典id
   * @returns number
   */
  delete(dictId) {
    return api.deleteDict(dictId).then((d) => {
      this.fetch();
      return d;
    });
  }

  /**
   * 返回当前页中的指定数据
   * @param {*} dictId
   * @returns dict
   */
  getDict(dictId) {
    const dict = this.data.find((d) => d.dictId === dictId);
    const promise = dict ? Promise.resolve(dict) : api.getDict(dictId);
    return promise;//.then((d) => { this.rootStore.dictItemStore.current = d; return d; });
  }

  /**
   * 计算表格中的索引
   * @param {number} i 表格说因
   * @returns 数据索引
   */
  idx(i) {
    return (this.pageNo - 1) * this.pageSize + i + 1;
  }
}
